package com.zxy.supplier_system.server.xinyuan.service

import com.zxy.supplier_system.server.utils.orElse404
import com.zxy.supplier_system.server.xinyuan.entity.XinyuanGoodsCategory
import com.zxy.supplier_system.server.xinyuan.repository.XinyuanGoodsCategoryRepository
import com.zxy.supplier_system.server.xinyuan.service.XinyuanGoodsCategoryService.CategoryResponse
import org.springframework.data.domain.Page
import org.springframework.data.domain.Pageable
import org.springframework.data.repository.findByIdOrNull
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional

@Service
class XinyuanGoodsCategoryService(
    private val xinyuanGoodsCategoryRepository: XinyuanGoodsCategoryRepository
) {

    // 创建分类
    @Transactional
    fun createCategory(request: CreateCategoryRequest): XinyuanGoodsCategory {
        return xinyuanGoodsCategoryRepository.save(
            XinyuanGoodsCategory().apply {
                name = request.name
                isHomeAppliance = request.isHomeAppliance
            }
        )
    }

    // 获取所有分类（分页）
    fun getAllCategories(pageable: Pageable): Page<CategoryResponse> {
        return xinyuanGoodsCategoryRepository.findAll(pageable)
            .map { it.toResponse() }
    }


    // 更新分类
    @Transactional
    fun updateCategory(id: Int, request: UpdateCategoryRequest): CategoryResponse {
        val category = xinyuanGoodsCategoryRepository.findByIdOrNull(id).orElse404()

        // 检查新名称是否已被其他分类使用

        category.name = request.name

        category.isHomeAppliance = request.isHomeAppliance

        return xinyuanGoodsCategoryRepository.save(category).toResponse()
    }

    // 删除分类
    @Transactional
    fun deleteCategory(id: Int) {
        xinyuanGoodsCategoryRepository.deleteById(id)
    }

    // 获取所有家电分类
    fun getAllHomeApplianceCategories(): List<CategoryResponse> {
        return xinyuanGoodsCategoryRepository.findByIsHomeAppliance(true)
            .map { it.toResponse() }
    }

    // 获取所有数码分类
    fun getAllDigitalCategories(): List<CategoryResponse> {
        return xinyuanGoodsCategoryRepository.findByIsHomeAppliance(false)
            .map { it.toResponse() }
    }



    // 请求和响应DTO
    data class CreateCategoryRequest(
        val name: String,
        val isHomeAppliance: Boolean
    )

    data class UpdateCategoryRequest(
        val name: String ,
        val isHomeAppliance: Boolean
    )

    data class CategoryResponse(
        val id: Int,
        val name: String,
        val isHomeAppliance: Boolean
    )
}

fun XinyuanGoodsCategory.toResponse(): CategoryResponse {
    return CategoryResponse(
        id = this.id,
        name = this.name,
        isHomeAppliance = this.isHomeAppliance
    )
}